<?php
namespace App\Models;

use App\Exceptions\ApiException;
use App\Models\Scope\ClientUserScope;
use Illuminate\Support\Facades\DB;

class ClientUser extends CommonModel {
	protected $table = 'client_user';
	
	/**
	 * 全局筛选用户类型作用域
	 */
	protected static function boot()
	{
		parent::boot();
		static::addGlobalScope(new ClientUserScope());
	}
	
	public function checkLogin($mobile,$password,$platform = []){
		$exist = $this->where(function($query) use($mobile,$platform){
			$query->where(['username'=>$mobile])->orWhere(['mobile'=>$mobile]);
		})->whereIn('type',$platform)->first();
		$password_gen = $this->passwordEncodeSalt($password,$exist->salt);
		if(empty($exist)){
			throw new ApiException('用户信息不存在');
		}
		if(strcmp($password_gen,$exist->password) !== 0){
			throw new ApiException('登录密码错误');
		}
		return $exist->id;
	}

	/**
	 * @return \Illuminate\Database\Eloquent\Relations\HasMany
	 * 业主家属信息
	 */
	public function family(){
		return $this->hasMany('\App\Models\ClientUserFamily','uid','id');
	}
	
	/**
	 * @return \Illuminate\Database\Eloquent\Relations\hasMany
	 * 租客、业主对应的房屋信息
	 */
	public function house(){
		return $this->hasMany('\App\Models\ClientUserHouse','house_id','id');
	}
	
	/**
	 * @param $query
	 * @param $password
	 * @param $salt
	 * @return string
	 * 根据明文密码和盐返回加密密码
	 */
	public function passwordEncodeSalt($password,$salt){
	     if(!$salt) {
               $password_gen = md5($password);
          }else{
               $password_gen = md5(md5($password) . $salt);
          }
		return $password_gen;
	}
	
	/**
	 * @param $username
	 * @param $mobile
	 * @param $password
	 * @return mixed
	 * 注册一个用户
	 */
	public function register($username,$mobile,$password){
           $house=HouseDistrictOwner::where(['mobile'=>$mobile])->where('house_id','>','0')->first();
           $check1=ClientUser::whereIn('type',['1','3'])->where(['mobile'=>$mobile])->first();
           $check2=ClientUser::whereIn('type',['1','3'])->where(['username'=>$username])->first();
            if($check1 || $check2){
                exit (json_encode(json_error('用户名或手机号已被注册')));
            }
           DB::beginTransaction();
           try {

                $salt = create_verify_code(6);
                $add = [
                    'username' => $username,
                    'mobile' => $mobile,
                    'password' => $this->passwordEncodeSalt($password, $salt),
                    'salt' => $salt,
                    'avatar' => config('basic.avatar'),
                    'type' => 3,     // 1业主，2物业，3租客，4商家
                    'status' => 1,
                ];
                if ($house) {
                     $add['type'] = 1;     // 如果有业主信息，就是业主
                     $add['realname'] = $house->realname;
                }

                $uid = static::create($add)->id;

                if(!$uid){
                     throw new \Exception("create error");
                }

                if($house) {
                     $parents_id = (new HouseDistrict)->getParentsId($house->house_id);
                     $bind = [
                         'uid' => $uid,
                         'house_id' => $house->house_id,
                         'floor_id' => $parents_id['0']['id'],
                         'village_id' => $parents_id['1']['id'],
                     ];
                     $bind_insert = ClientUserHouse::create($bind);
                     if (!$bind_insert) {
                          throw new \Exception("bind error");
                     }
                }
                DB::commit();

           } catch (\Exception $e){
                DB::rollback();
                exit (json_encode(json_error($e->getMessage())));
           }

           return $uid;

	}

    /**
     * @param $username
     * @param $mobile
     * @param $password
     * @return mixed
     * 注册一个商家
     */
	public function SellerRegister($username,$mobile,$password){
        $check1=ClientUser::whereIn('type',['4'])->where(['mobile'=>$mobile])->first();
        $check2=ClientUser::whereIn('type',['4'])->where(['username'=>$username])->first();
        if($check1 || $check2){
            exit (json_encode(json_error('用户名或手机号已被注册')));
        }
        DB::beginTransaction();
        try {
            $salt = create_verify_code(6);
            $add = [
                'username' => $username,
                'mobile' => $mobile,
                'password' => $this->passwordEncodeSalt($password, $salt),
                'salt' => $salt,
                'avatar' => config('basic.avatar'),
                'type' => 4,     // 1业主，2物业，3租客，4商家
                'status' => 1,
            ];

            $uid = static::create($add)->id;

            $store_add = [
                'uid'=>$uid,
                'status'=>2,
                'is_del'=>0
            ];
            $store_id = ShopStore::create($store_add)->id;

            $role_add = [
                'uid'=>$uid,
                'store_id'=>$store_id,
                'group_id'=>1,
                'username'=>$username,
                'mobile'=>$mobile
            ];
            $role_id = ShopStoreRoles::create($role_add)->id;
            $account_add = ['uid'=>$uid,'amount'=>'0'];
            $account_id = Account::create($account_add)->id;
            if(!$uid || !$store_id || !$role_id || !$account_id){
                throw new \Exception("注册失败!");
            }
            DB::commit();
        } catch (\Exception $e){
            DB::rollback();
            exit (json_encode(json_error($e->getMessage())));
        }
        return $uid;
    }


	/**
	 * 只列出能展示的字段
	 */
	public function scopeList($query){
		$query->select(['id','username','realname','mobile','email','avatar','gender','signature','created_at','type']);
	}
	
	/**
	 * @param $query
	 * 只查询业主用户
	 */
	public function scopeClient($query){
		$query->where(['client_user.type'=>1]);
	}
	
	/**
	 * @param $query
	 * 只查询楼管(物业人员)用户
	 */
	public function scopeManager($query){
		$query->where(['client_user.type'=>2]);
	}
	
	/**
	 * @param $query
	 * 只查询租客信息
	 */
	public function scopeRenter($query){
		$query->where(['client_user.type'=>3]);
	}
	
	/**
	 * @param $query
	 * 只查询商家信息
	 */
	public function scopeBusiness($query){
		$query->where(['client_user.type'=>4]);
	}
}